<template>
  <div class="common-dialog">
    <el-dialog
      :title="title"
      width="50%"
      :model-value="props.modelValue"
      @update:modelValue="closeDialog"
    >
      <el-form
        label-width="120px"
        class="dialog-form"
        :model="formData"
        :rules="formRules"
        ref="formRef"
        
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="商品标题:" prop="title">
              <el-input v-model="formData.title" placeholder="请输入商品标题" :disabled="isReviewMode"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="商品价格:" prop="price">
              <el-input-number
                v-model="formData.price"
                :min="0"
                :step="1"
                placeholder="请输入商品价格"
                style="width: 100%"
                :disabled="isReviewMode"
              >
              </el-input-number>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="总数量:" prop="number">
              <el-input-number
                v-model="formData.number"
                :min="1"
                :step="1"
                placeholder="请输入商品总数"
                style="width: 100%"
                :disabled="isReviewMode"
              >
              </el-input-number>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="新旧程度:" prop="condition">
              <el-select
                v-model="formData.condition"
                placeholder="请选择新旧程度"
                style="width: 100%"
                :disabled="isReviewMode"
              >
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="商品分类:" prop="categoryId">
              <el-select
                v-model="formData.categoryId"
                placeholder="请选择商品分类"
                style="width: 100%"
                :disabled="isReviewMode"
              >
                <el-option
                  v-for="category in categories"
                  :key="category.id"
                  :label="category.categoryName"
                  :value="category.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="商品属性:" prop="categoryTypeId">
              <el-tree-select
                v-model="formData.categoryTypeId"
                :data="productTypes"
                :render-after-expand="false"
                style="width: 100%"
                :disabled="isReviewMode"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="商品品牌:" prop="brandId">
              <el-select
                v-model="formData.brandId"
                placeholder="请选择商品品牌"
                style="width: 100%"
                :disabled="isReviewMode"
              >
                <el-option
                  v-for="brand in brands"
                  :key="brand.id"
                  :label="brand.name"
                  :value="brand.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <!-- 商品状态字段仅在审核模式下显示 -->
          <el-col :span="12" v-if="isReviewMode">
            <el-form-item label="商品状态:" prop="status">
              <el-select v-model="formData.status" placeholder="请选择商品状态" style="width: 100%">
                 <el-option
                  v-for="status in statusOptions"
                  :key="status.value"
                  :label="status.label"
                  :value="status.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="首页商品图片:" prop="homeImage">
          <el-upload
             v-model:file-list="homeImageList"
            action="http://localhost:9093/file/upload"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleHomeImageRemove"
            :on-success="handleHomeImageSuccess"
            :limit="1"
            :on-exceed="handleHomeImageExceed"
            :disabled="isReviewMode"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
          <el-dialog v-model="dialogVisible">
            <img w-full :src="dialogImageUrl" alt="Preview Image" />
          </el-dialog>
        </el-form-item>

        <el-form-item label="商品展示图片:" prop="image">
          <el-upload
            ref="imageUploadRef"
            v-model:file-list="fileList"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleImageRemove"
            :auto-upload="false"
            multiple
            :limit="5"
            :on-exceed="handleImageExceed"
            name="files"
            :disabled="isReviewMode"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
          <el-dialog v-model="dialogVisible">
            <img w-full :src="dialogImageUrl" alt="Preview Image" />
          </el-dialog>

          <div class="upload-btn-group" v-if="!isReviewMode">
            <el-button type="primary" @click="submitUpload">上传所有图片</el-button>
            <el-button @click="clearFiles">清空列表</el-button>
          </div>
        </el-form-item>

        <el-form-item label="商品描述:" prop="description">
          <el-input
            v-model="formData.description"
            type="textarea"
            :autosize="{ minRows: 4, maxRows: 6 }"
            placeholder="请输入商品描述"
            :disabled="isReviewMode"
          />
        </el-form-item>

        <el-form-item label="备注:">
          <el-input
            v-model="formData.remark"
            type="textarea"
            :autosize="{ minRows: 2, maxRows: 4 }"
            placeholder="请输入备注信息"
            :disabled="isReviewMode"
          />
        </el-form-item>

        <el-form-item >
          <el-button type="primary" @click="saveProduct">保存</el-button>
          <el-button @click="closeDialog">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script lang="js" setup>
import { ref, defineProps, defineEmits, watch, computed } from "vue";
import { ElMessage } from "element-plus";
import instance from "@/utils/request";
import { Plus } from '@element-plus/icons-vue'

const title = ref("添加商品");
const formRef = ref(null);
const dialogVisible = ref(false);
const dialogImageUrl = ref('');
const imageUploadRef = ref(null);
const fileList = ref([]);
const formData = ref({
  id: '',
  title: '',
  homeImage: '',
  image: [],
  price: null,
  categoryId: null,
  categoryTypeId: null,
  brandId: null,
  status: null,
  number: null,
  sold: 0,
  description: '',
  condition: '',
  remark: ''
});

// 接收父组件传递的值
const props = defineProps({
  modelValue: Boolean,
  newFormData: Object,
  // 添加操作模式属性：'user' 表示用户操作，'review' 表示管理员审核
  operationMode: {
    type: String,
    default: 'user' // 默认为用户操作模式
  }
});

// 计算属性：是否为审核模式
const isReviewMode = computed(() => {
  return props.operationMode === 'review';
});

// 计算属性：是否为用户操作模式
const isUserMode = computed(() => {
  return props.operationMode === 'user';
});

// 根据操作模式设置标题
watch(isReviewMode, (newVal) => {
  if (newVal) {
    title.value = '审核商品';
  } else {
    title.value = formData.value.id ? '修改商品' : '添加商品';
  }
}, { immediate: true });

const statusOptions = [
  {
    value: 0,
    label: '待审核'
  },
  {
    value: 1,
    label: '已通过'
  },
  {
    value: 2,
    label: '已驳回'
  },
  {
    value: 3,
    label: '待发布'
  },
]

const options = [
  {
    value: 0,
    label: '全新'
  },
  {
    value: 1,
    label: '九成新'
  },
  {
    value: 2,
    label: '八成新'
  },
  {
    value: 3,
    label: '七成新'
  },
  {
    value: 4,
    label: '六成新'
  },
  {
    value: 5,
    label: '五成新'
  },
  {
    value: 6,
    label: '四成新'
  },
  {
    value: 7,
    label: '其他'
  }
]

// 计算属性：将homeImage转换为upload组件需要的格式
const homeImageList = computed(() => {
  if (formData.value.homeImage) {
    return [{
      name: 'homeImage',
      url: formData.value.homeImage
    }];
  }
  return [];
});

// 表单验证规则
const formRules = {
  title: [
    { required: true, message: '请输入商品标题', trigger: 'blur' }
  ],
  price: [
    { required: true, message: '请输入商品价格', trigger: 'blur' }
  ],
  number: [
    { required: true, message: '请输入商品总数', trigger: 'blur' }
  ],
  condition: [
    { required: true, message: '请选择新旧程度', trigger: 'change' }
  ],
  categoryId: [
    { required: true, message: '请选择商品分类', trigger: 'change' }
  ],
  categoryTypeId: [
    { required: true, message: '请选择商品属性', trigger: 'change' }
  ],
  brandId: [
    { required: true, message: '请选择商品品牌', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择商品状态', trigger: 'change' }
  ],
  homeImage: [
    { required: true, message: '请上传首页图片', trigger: 'change' }
  ],
  description: [
    { required: true, message: '请输入商品描述', trigger: 'blur' }
  ]
};

// 分类、类型、品牌数据
const categories = ref([]);
const productTypes = ref([]);
const brands = ref([]);

// 定义向父组件发送的事件
const emit = defineEmits(["update:modelValue", "update"]);

watch(() => props.newFormData, (newValue) => {
  if (newValue) {
    formData.value = JSON.parse(JSON.stringify(newValue));
        formData.value.brandId = Number(formData.value.brandId);
        formData.value.categoryTypeId = Number(formData.value.categoryTypeId);
        formData.value.categoryId = Number(formData.value.categoryId);
         // 添加对展示图片的处理
    if (newValue.image && Array.isArray(newValue.image)) {
      fileList.value = newValue.image.map((url, index) => ({
        name: `image-${index}`,
        url: url
      }));
    } else {
      fileList.value = [];
    }
  }

  // 根据是否有id来设置标题
  if (formData.value.id) {
    title.value = '修改商品';
  } else {
    title.value = '添加商品';
  }
}, { immediate: true });

// 首页图片上传成功处理
const handleHomeImageSuccess = (response) => {
  if (response && response.code === 200) {
    formData.value.homeImage = response.data; // 假设后端返回的图片URL在data字段中
    ElMessage.success('首页图片上传成功');
  } else {
    ElMessage.error('首页图片上传失败');
  }
};

// 首页图片移除处理
const handleHomeImageRemove = () => {
  formData.value.homeImage = '';
  ElMessage.info('首页图片已移除');
};

// 展示图片移除处理
const handleImageRemove = (file) => {
  if (formData.value.image && formData.value.image.length > 0) {
    const index = formData.value.image.findIndex(img => img === file.url);
    if (index > -1) {
      formData.value.image.splice(index, 1);
      ElMessage.info('展示图片已移除');
    }
  }
};

// 图片预览处理
const handlePictureCardPreview = (file) => {
  dialogImageUrl.value = file.url;
  dialogVisible.value = true;
};

// 首页图片上传超出限制处理
const handleHomeImageExceed = () => {
  ElMessage.warning('首页商品图片只能上传一张！');
};

// 展示图片上传超出限制处理
const handleImageExceed = () => {
  ElMessage.warning('商品展示图片最多只能上传5张！');
};

// 获取商品分类列表
const getCategories = async () => {
  try {
    const response = await instance.get('category/getAllCategory');
    if (response.data.code === 200) {
      categories.value = response.data.data.records;
    }
  } catch (error) {
    console.error('获取商品分类列表失败:', error);
  }
};

// 获取商品属性列表
const getProductTypes = async () => {
  try {
    const response = await instance.get('/type/listType');
    if (response.data.code === 200) {
      productTypes.value = response.data.data;
    }
  } catch (error) {
    console.error('获取商品属性列表失败:', error);
  }
};

// 获取品牌列表
const getBrands = async () => {
  try {
    const response = await instance.get('/brand/getBrandList');
    if (response.data.code === 200) {
      brands.value = response.data.data.records;
    }
  } catch (error) {
    console.error('获取品牌列表失败:', error);
  }
};

// 提交上传所有图片
const submitUpload = async() => {
  console.log('提交上传所有图片',fileList.value);
  if (fileList.value.length === 0) {
    ElMessage.warning('请先选择要上传的图片');
    return;
  }
 // 创建 FormData 对象用于上传文件
  const uploadFormData  = new FormData();
  // 将所有文件添加到 FormData 中，使用 'files' 作为字段名与后端接口匹配
  let validFileCount = 0;
  fileList.value.forEach(file => {
    // 使用 file.raw 获取原始文件对象（Element Plus Upload 组件的结构）
    const rawFile = file.raw || file; // 兼容不同版本
    if (rawFile instanceof File) {
      uploadFormData.append('files', rawFile);
      validFileCount++;
    }
  });
    // 检查是否有有效文件
  if (validFileCount === 0) {
    ElMessage.warning('没有有效的文件需要上传');
    return;
  }
  try {
    const response = await instance.post('/file/listUpload', uploadFormData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    });
    console.log('所有图片上传响应:', response);
    if (response.data && response.data.code === 200) {
      formData.value.image = [...response.data.data];
      ElMessage.success('所有图片上传成功');
    } else {
      ElMessage.error('所有图片上传失败');
    }
  } catch (error) {
    console.error('所有图片上传失败:', error);
  }
};

// 保存商品
const saveProduct = async () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        let response;
         console.log('发送到后端的数据:', formData.value);
        if (formData.value.id) {
          // 修改商品
          response = await instance.put('/product/edit', formData.value);
        } else {
          // 添加商品
          response = await instance.post('/product/add', formData.value);
        }
        console.log('保存商品响应:', response);
        console.log('保存的商品数据:', formData.value);
        if (response.data.code === 200) {
          ElMessage.success(formData.value.id ? "修改成功！" : "添加成功！");
          emit("update", response.data);
          closeDialog();
        } else {
          ElMessage.error(formData.value.id ? "修改失败！" : "添加失败！");
        }
      } catch (error) {
        ElMessage.error("操作失败！" + error);
      }
    } else {
      ElMessage.error("请填写必填项");
      return false;
    }
  });
};

// 关闭弹窗方法
const closeDialog = () => {
  formRef.value.resetFields();
  emit("update:modelValue", false);
};

// 组件挂载时获取下拉选项数据
getCategories();
getProductTypes();
getBrands();
</script>

<style scoped>
.dialog-form {
  padding: 20px;
}
</style>